package sk.demo.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import sk.demo.jpa.entity.Message;

import java.util.Date;
import java.util.List;
import java.util.Scanner;

/**
 * @author sk.z
 */
@Service
public class Console {

    @Autowired
    private MessageService messageService;

    public void cmd() {
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.print("cmd:>");
            while (scanner.hasNextLine()) {
                try {
                    String cmd = scanner.nextLine();
                    if ("test".equals(cmd)){
                        List<Message> list = messageService.getByContent("德化县教育局");
                        list.forEach(e -> System.out.println(e.toString()));
                    }else
                    if ("user".equals(cmd)) {
                        List<Message> list = messageService.getByUser("10001");
                        list.forEach(e -> System.out.println(e.toString()));
                    } else if ("page".equals(cmd)) {
                        List<Message> list = messageService.page(1, 5);
                        list.forEach(e -> System.out.println(e.toString()));
                    } else if ("save".equals(cmd)) {
                        System.out.println("new record id is : " + messageService.saveRandom());
                    } else if ("find one".equals(cmd)) {
                        messageService.getById(1L);
                    } else if ("time".equals(cmd)) {
                        System.out.println(new Date());
                    } else if ("exit".equals(cmd)) {
                        break;
                    } else {
                        System.out.println("un know cmd : " + cmd);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.print("cmd:>");
            }
        }).start();
    }

    @EventListener
    public void onHandler(ApplicationReadyEvent event) {
        cmd();
    }
}
